
package mwn.droidbus.directions;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.http.util.ByteArrayBuffer;
import java.util.ArrayList;  
import com.google.android.maps.GeoPoint;



//request data from google maps : two points, flag for public transport, and output type kml
//- get kml file back

//this doesnt work!!!!!!!!!  works until publc trans flag set - kml file is empty!

public class MapsScraper { //get the data from google

	
	
	    
	//http://maps.google.com/maps?f=d&hl=en&saddr=-34.92883,138.55741&daddr=-34.92777,138.60411&ie=UTF8&0&om=0&output=kml
	// http://maps.google.com/maps?f=d&hl=en&saddr=25.04202,121.534761&daddr=25.05202,121.554761&ie=UTF8&0&om=0&output=kml&dirflg=r  ---> works!
	// http://www.google.com/maps?ie=UTF8&f=d&dirflg=r&hl=en&saddr=<<<src addr>>>&daddr=<<<dest addr>>>&ttype=dep&date=10%2F19%2F10&time=8%3A04pm
	
	
	//dirflg=r    ----> public transit
	//http://maps.google.com/maps?saddr=&daddr=&sll=&dirflg=w&hl=en&ie=UTF8&z=14&output=kml
	//http://maps.google.com/maps?saddr=&daddr=&sll=&hl=en&ie=UTF8&z=14&output=kml
	
	
	
	//setup the request
	public ArrayList<GeoPoint> calculateRoute(String startCoords, String targetCoords ){
	
	   String reqst = "http://maps.google.com/maps?f=d&hl=en&saddr=-34.92883,138.55741&daddr=-34.92777,138.60411&ie=UTF8&0&om=0&output=kml";
	    
	
	   ArrayList<GeoPoint> navSet = null;
	    
	    navSet = download( reqst );
	    
	    return navSet;
	}
	
	
	 
	 //make request
	public ArrayList<GeoPoint> download( String urlstring ) {  
		
		try {
			URL url = new URL( urlstring ); 
		    File file = new File( "maps.kml" );
		    
		    URLConnection uc = url.openConnection();    
		    InputStream is = uc.getInputStream();
		    BufferedInputStream bis = new BufferedInputStream(is);
		                              
		    ByteArrayBuffer bab = new ByteArrayBuffer(100);
		    int count = 0;
		    while (  ( count = bis.read() ) != -1  ){  //rcv data
		    	bab.append((byte) count);
		    }
		    FileOutputStream fos = new FileOutputStream(file);
		    fos.write(bab.toByteArray());
		    fos.close();
		    
		}catch (IOException e) {
			//die
		}
		
		return KmlParser.parse( "maps.kml" );
		
	}//download

}//class
